// pages/address/address.js
//获取应用实例
const app = getApp();
const util = require('../../utils/util.js')
const api = require('../../utils/api.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //获取全局变量 导航栏的高度statusBarHeight
    statusBarHeight: app.globalData.statusBarHeight,
    // 胶囊
    jiaonang: app.globalData.jiaonang, 
    navigationHeight: app.globalData.navigationHeight,
    // pageTitle
    pageTitle: '管理地址',
    // 地址
    addressListData: [],
    // 保存方式
    handleStatus: true, // true：新增。false:编辑。
    // 新增/编辑地址
    addOrEditAddress:{id:null,consignee:'',mobile:'',address_time:'',region:'',address:'',default:0},
    // 添加或编辑弹出框
    addOrEditAddressShow: false,
    // 默认地址
    switchChecked: false,
    timePicker: ['收货时间不限', '周六日/节假日收货', '周一至周五收货'],
    // 省市区
    region: ['', '', ''],
    // 选择地址
    choose: false,
    // 下单的商品id
    orderGoods: [],
    // 是否直接购买
    isDirect: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let newPageTitle = '';
    let choose = null;
    let carListIdData = [];
    let goods ={};
    // 确认订单选择收货地址
    if(options.chooes){
      newPageTitle = '选择收货地址';
      choose = options.chooes;
    }
    // 购物车购买
    if(options.carListIdData){
      carListIdData = JSON.parse(options.carListIdData);
      this.setData({
        pageTitle: newPageTitle,
        choose,
        orderGoods: carListIdData,
        isDirect: false
      })
    }
    // 商品详情直接购买
    if(options.goods){
      goods = JSON.parse(options.goods);
      console.log('商品详情直接购买',goods);
      this.setData({
        pageTitle: newPageTitle,
        choose,
        goods,
        isDirect: true
      })
    }
    
    // 获取收货地址
    this.getAddressListData();
  },
  // 获取收货地址
  getAddressListData:function(){
    api.getAddress().then(res => {
      if(res.code == 0){
        this.setData({
          addressListData: res.data.data
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  // 返回上一级
  back:function(){
    let addOrEditAddressShow=this.data.addOrEditAddressShow;
    let choose = this.data.choose;
    if(addOrEditAddressShow && !choose){
      this.setData({
        addOrEditAddressShow:false,
        pageTitle: '管理地址'
      })
    }else if(addOrEditAddressShow && choose){
      this.setData({
        addOrEditAddressShow:false,
        pageTitle: '选择收货地址'
      })
    }else if(!choose){
      wx.reLaunch({
        url: '/pages/personal/personal'
      })
    }else{
      wx.navigateBack({
        delta: 1
      })
    }
  },
  // 选择地址
  chooseAddress:function(e){
    if(this.data.choose){
      if(this.data.isDirect){
        wx.reLaunch({
          url: `/pages/pay/pay?addressId=${e.currentTarget.dataset.id}&goods=${JSON.stringify(this.data.goods)}`
        })
      }else{
        wx.reLaunch({
          url: `/pages/pay/pay?addressId=${e.currentTarget.dataset.id}&orderGoods=${JSON.stringify(this.data.orderGoods)}`
        })
      }
      
    }
  },
  // 新增地址
  addAddress:function(){
    this.setData({
      handleStatus:true,
      addOrEditAddress:{id:null,consignee:'',mobile:'',address_time:'',region:'',address:'',default:false},
      addOrEditAddressShow: true,
      pageTitle: '新增地址',
    })
  },
  // 编辑地址
  editAddress:function(e){
    this.setData({
      handleStatus:false,
      addOrEditAddress: e.currentTarget.dataset.item,
      addOrEditAddressShow: true,
      pageTitle: '编辑地址',
    })
  },
  // 删除地址
  deleteAddress:function(e){
    let that = this;
    let addressId =e.currentTarget.dataset.id;
    let addressListData = this.data.addressListData;
    let addressDetail = ''
    if(addressId){
      addressListData.forEach(item => {
        if(item.address_id == addressId){
          addressDetail = item.region + item.address;
        }
      })
      wx.showModal({
        title: '确定删除以下地址？',
        content: addressDetail,
        success (res) {
          if (res.confirm) {
            api.deleteAddress(addressId).then(res => {
              if(res.code == 0){
                wx.showToast({
                  title: res.msg,
                  icon: 'success',
                  duration: 1500
                })
                that.getAddressListData();
              }else{

              }
            })
          }
        }
      })
    }
  },
  // 背景不滚动
  dontMove: function(){
    return;
  },
  // 收起键盘
  hideKeyboard:function(){
    wx.hideKeyboard();
  },
  // 收货人
  bindName:function(e){
    this.setData({
      'addOrEditAddress.consignee': e.detail.value
    })
  },
  // 手机号
  bindPhone:function(e){
    this.setData({
      'addOrEditAddress.mobile': e.detail.value
    })
  },
  // 收货时间
  bindTimePickerChange:function(e){
    let i = e.detail.value;
    wx.hideKeyboard();
    this.setData({
      'addOrEditAddress.address_time': this.data.timePicker[i]
    })
  },
  // 省市区
  bindRegionChange:function(e){
    this.setData({
      'addOrEditAddress.region': e.detail.value[0]+e.detail.value[1]+e.detail.value[2]
    })
  },
  // 详细地址
  bindDetailAddress:function(e){
    this.setData({
      'addOrEditAddress.address': e.detail.value
    })
  },
   // 默认地址
   defautAddress:function(e){
    this.setData({
      'addOrEditAddress.default': e.detail.value?1:0
    })
  },
  // 保存
  save:function(){
    let that = this;
    let addOrEditAddress = this.data.addOrEditAddress;
    for(let i in addOrEditAddress){
      if(!util.checkEmpty(addOrEditAddress[i])){
        addOrEditAddress[i] = util.trimStr(addOrEditAddress[i])
      }
    }
    if(util.checkEmpty(addOrEditAddress.consignee)){
      wx.showToast({
        title: '请填写收货人姓名',
        icon: 'none',
        duration: 2000
      })
      return false;
    }
    if(!util.checkPhone(addOrEditAddress.mobile) || util.checkEmpty(addOrEditAddress.mobile)){
      wx.showToast({
        title: '收货人手机号码不正确',
        icon: 'none',
        duration: 2000
      })
      return false;
    }
    if(util.checkEmpty(addOrEditAddress.address_time)){
      wx.showToast({
        title: '请选择收货时间',
        icon: 'none',
        duration: 2000
      })
      return false;
    }
    if(util.checkEmpty(addOrEditAddress.region)){
      wx.showToast({
        title: '请选择省市区',
        icon: 'none',
        duration: 2000
      })
      return false;
    }
    if(util.checkEmpty(addOrEditAddress.address)){
      wx.showToast({
        title: '请填写详细地址',
        icon: 'none',
        duration: 2000
      })
      return false;
    }
    // 新增地址
    if(that.data.handleStatus){
      api.addAddress(that.data.addOrEditAddress).then(res => {
        if(res.code == 0){
          that.handleSuccess();
          that.getAddressListData();
        }else{
          wx.showToast({
            title: res.msg,
            icon: 'error',
            duration: 2000
          })
          
        }
      })
    }else{ // 编辑地址
      api.editAddress(that.data.addOrEditAddress).then(res => {
        if(res.code == 0){
          wx.showToast({
            title: res.msg,
            icon: 'success'
          })
          this.getAddressListData();
        }
      })
    }
  },
  // 添加成功
  handleSuccess:function(){
    let that = this;
    wx.showToast({
      title: '保存成功',
      icon: 'success',
      duration: 2000,
      success:function(){
        if(that.data.choose){
          that.setData({
            addOrEditAddress: {id:null,consignee:'',mobile:'',address_time:'',region:'',address:'',default:0},
            addOrEditAddressShow: false,
            pageTitle: '选择收货地址',
          })
        }else{
          that.setData({
            addOrEditAddress: {id:null,consignee:'',mobile:'',address_time:'',region:'',address:'',default:0},
            addOrEditAddressShow: false,
            pageTitle: '管理地址',
          })
        }
        
      }
    })
  }
})